#include "componentdialog.h"
#include "supplierdialog.h"
#include <QLineEdit>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QString>
#include <QValidator>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QDebug> // 添加 qDebug 头文件
#include <QPalette>
#include <QComboBox>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <cstring> // For strncpy

extern "C" {
#include "../backend/component.h"
#include "../backend/supplier.h"
}

ComponentDialog::ComponentDialog(QWidget* parent, const Component* init, bool idEditable, SupplierNode* suppliers)
    : QDialog(parent), supplierHead(suppliers)
{
    setWindowTitle(init ? "编辑组件" : "添加组件");
    QFormLayout* form = new QFormLayout(this);

    idEdit = new QLineEdit;
    modelEdit = new QLineEdit;
    nameEdit = new QLineEdit;
    packageEdit = new QLineEdit;
    descEdit = new QLineEdit;
    qtyEdit = new QLineEdit;
    priceEdit = new QLineEdit;
    
    // 供应商选择组合框和相关控件
    supplierComboBox = new QComboBox;
    supplierInfoLabel = new QLabel("请选择供应商");
    addSupplierBtn = new QPushButton("添加新供应商");
    
    // 设置验证器
    setupValidators();
    
    // 初始化供应商组合框
    setupSupplierComboBox();

    // 根据 C 结构体定义设置最大长度
    modelEdit->setMaxLength(30);
    nameEdit->setMaxLength(50);
    packageEdit->setMaxLength(20);
    descEdit->setMaxLength(200);

    form->addRow("ID (1-10位数字):", idEdit);
    form->addRow("型号 (字母数字-_，2-30字符):", modelEdit);
    form->addRow("名称 (英文数字，1-50字符):", nameEdit);
    form->addRow("封装 (大写字母数字，2-20字符):", packageEdit);
    form->addRow("描述 (可选，最多200字符):", descEdit);
    
    // 供应商选择区域
    QHBoxLayout* supplierLayout = new QHBoxLayout;
    supplierLayout->addWidget(supplierComboBox);
    supplierLayout->addWidget(addSupplierBtn);
    form->addRow("供应商:", supplierLayout);
    form->addRow("", supplierInfoLabel);
    
    form->addRow("库存 (0-999999):", qtyEdit);
    form->addRow("价格 (0.01-99999.99):", priceEdit);

    if (init) {
        idEdit->setText(QString::number(init->id));
        modelEdit->setText(init->model);
        nameEdit->setText(init->name);
        packageEdit->setText(init->package);
        descEdit->setText(init->description);
        qtyEdit->setText(QString::number(init->quantity));
        priceEdit->setText(QString::number(init->price, 'f', 2));
        
        // 设置供应商选择
        for (int i = 0; i < supplierComboBox->count(); ++i) {
            if (supplierComboBox->itemData(i).toInt() == init->supplier_id) {
                supplierComboBox->setCurrentIndex(i);
                break;
            }
        }
        
        if (!idEditable) {
            idEdit->setReadOnly(true);
        }
    }

    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, this, &ComponentDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &ComponentDialog::reject);
    
    // 连接实时验证信号
    connect(idEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(modelEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(nameEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(packageEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(descEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(qtyEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    connect(priceEdit, &QLineEdit::textChanged, this, &ComponentDialog::validateInput);
    
    // 连接供应商相关信号
    connect(supplierComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &ComponentDialog::onSupplierSelectionChanged);
    connect(addSupplierBtn, &QPushButton::clicked, this, &ComponentDialog::onAddSupplierClicked);
    
    // 初始化供应商信息显示
    updateSupplierInfo();
}

void ComponentDialog::setupValidators() {
    // ID验证器：1-10位数字
    QRegularExpressionValidator* idValidator = new QRegularExpressionValidator(
        QRegularExpression("^[1-9]\\d{0,9}$"), this);
    idEdit->setValidator(idValidator);
    
    // 型号验证器：字母数字-_，无空格
    QRegularExpressionValidator* modelValidator = new QRegularExpressionValidator(
        QRegularExpression("^[A-Za-z0-9_-]{2,30}$"), this);
    modelEdit->setValidator(modelValidator);
    
    // 名称验证器：中英文数字，允许空格 (临时修改为 .*)
    QRegularExpression compNameRegex(QStringLiteral("^[a-zA-Z0-9]{1,50}$"));
    qDebug() << "ComponentDialog Name - Pattern:" << compNameRegex.pattern()
             << "Valid:" << compNameRegex.isValid()
             << "Error:" << compNameRegex.errorString();
    QValidator *compNameValidator = new QRegularExpressionValidator(compNameRegex, this);
    nameEdit->setValidator(compNameValidator);
    
    // 封装验证器：大写字母数字
    QRegularExpressionValidator* packageValidator = new QRegularExpressionValidator(
        QRegularExpression("^[A-Z0-9]{2,20}$"), this);
    packageEdit->setValidator(packageValidator);
    
    // 库存验证器：非负整数
    QRegularExpressionValidator* qtyValidator = new QRegularExpressionValidator(
        QRegularExpression("^(0|[1-9]\\d{0,5})$"), this);
    qtyEdit->setValidator(qtyValidator);
    
    // 价格验证器：正数，最多2位小数
    QRegularExpressionValidator* priceValidator = new QRegularExpressionValidator(
        QRegularExpression("^(0\\.(0[1-9]|[1-9]\\d)|[1-9]\\d{0,4}(\\.\\d{1,2})?)$"), this);
    priceEdit->setValidator(priceValidator);
}

void ComponentDialog::setupSupplierComboBox() {
    supplierComboBox->clear();
    supplierComboBox->addItem("请选择供应商", -1);
    
    SupplierNode* current = supplierHead;
    while (current) {
        QString itemText = QString("ID:%1 - %2").arg(current->data.id).arg(current->data.name);
        supplierComboBox->addItem(itemText, current->data.id);
        current = current->next;
    }
    
    if (supplierComboBox->count() == 1) {
        supplierInfoLabel->setText("暂无可用供应商，请先添加供应商");
        supplierInfoLabel->setStyleSheet("color: red;");
    }
}

void ComponentDialog::updateSupplierInfo() {
    int supplierId = supplierComboBox->currentData().toInt();
    if (supplierId == -1) {
        supplierInfoLabel->setText("请选择供应商");
        supplierInfoLabel->setStyleSheet("color: gray;");
        return;
    }
    
    SupplierNode* supplier = find_supplier_by_id(supplierHead, supplierId);
    if (supplier) {
        QString info = QString("联系人：%1，电话：%2")
                      .arg(supplier->data.contact_person)
                      .arg(supplier->data.phone);
        supplierInfoLabel->setText(info);
        supplierInfoLabel->setStyleSheet("color: green;");
    } else {
        supplierInfoLabel->setText("供应商信息未找到");
        supplierInfoLabel->setStyleSheet("color: red;");
    }
}

void ComponentDialog::onSupplierSelectionChanged() {
    updateSupplierInfo();
}

void ComponentDialog::onAddSupplierClicked() {
    SupplierDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        // 添加新供应商到列表
        if (add_supplier(&supplierHead, &dialog.data)) {
            // 重新初始化组合框
            setupSupplierComboBox();
            
            // 选中新添加的供应商
            for (int i = 0; i < supplierComboBox->count(); ++i) {
                if (supplierComboBox->itemData(i).toInt() == dialog.data.id) {
                    supplierComboBox->setCurrentIndex(i);
                    break;
                }
            }
            
            QMessageBox::information(this, "成功", "新供应商添加成功");
        } else {
            QMessageBox::warning(this, "错误", "添加供应商失败，ID可能已存在");
        }
    }
}

void ComponentDialog::validateInput() {
    QLineEdit* sender = qobject_cast<QLineEdit*>(QObject::sender());
    if (!sender) return;
    
    QPalette palette;
    bool isValid = true;
    QString tooltip;
    
    if (sender == idEdit) {
        int id = idEdit->text().toInt();
        isValid = validate_component_id(id);
        tooltip = isValid ? "" : "ID必须是1-10位的正整数";
    } else if (sender == modelEdit) {
        QByteArray modelBytes = modelEdit->text().toUtf8();
        isValid = validate_component_model(modelBytes.constData());
        tooltip = isValid ? "" : "型号必须是2-30个字符的字母数字组合（可含-_），不能有空格";
    } else if (sender == nameEdit) {
        QByteArray nameBytes = nameEdit->text().toUtf8();
        isValid = validate_component_name(nameBytes.constData());
        tooltip = isValid ? "" : "名称必须是1-50个字符，支持中英文和数字，不能有特殊符号（空格除外）";
    } else if (sender == packageEdit) {
        QByteArray packageBytes = packageEdit->text().toUtf8();
        isValid = validate_component_package(packageBytes.constData());
        tooltip = isValid ? "" : "封装必须是2-20个字符的大写字母和数字组合";
    } else if (sender == descEdit) {
        QByteArray descBytes = descEdit->text().toUtf8();
        isValid = validate_component_description(descBytes.constData());
        tooltip = isValid ? "" : "描述不能超过200个字符，且不能包含恶意脚本标签";
    } else if (sender == qtyEdit) {
        int qty = qtyEdit->text().toInt();
        isValid = validate_component_quantity(qty);
        tooltip = isValid ? "" : "库存必须是0-999999的非负整数";
        
        // 特殊处理：库存=0时标记"缺货"
        if (qty == 0 && isValid) {
            tooltip = "注意：库存为0，标记为缺货状态";
            palette.setColor(QPalette::Base, QColor(255, 255, 200)); // 淡黄色背景
        }
    } else if (sender == priceEdit) {
        // 清理价格字符串
        QString cleanPrice = priceEdit->text();
        QByteArray priceBytes = cleanPrice.toUtf8();
        char* priceStr = strdup(priceBytes.constData());
        clean_price_string(priceStr);
        
        float price = QString(priceStr).toFloat();
        isValid = validate_component_price(price);
        tooltip = isValid ? "" : "价格必须是0.01-99999.99的正数，最多2位小数";
        free(priceStr);
    }
    
    if (!isValid) {
        palette.setColor(QPalette::Base, QColor(255, 200, 200)); // 淡红色背景
    }
    
    sender->setPalette(palette);
    sender->setToolTip(tooltip);
}

void ComponentDialog::accept() {
    // 在填充之前清除结构体以避免残留数据
    memset(&data, 0, sizeof(Component));

    // 获取并验证数据
    bool ok_id, ok_qty;
    data.id = idEdit->text().toInt(&ok_id);
    data.supplier_id = supplierComboBox->currentData().toInt();
    data.quantity = qtyEdit->text().toInt(&ok_qty);
    
    // 检查供应商是否已选择
    if (data.supplier_id == -1) {
        QMessageBox::warning(this, "数据验证失败", "请选择供应商");
        return;
    }
    
    // 清理价格字符串
    QString cleanPrice = priceEdit->text();
    QByteArray priceBytes = cleanPrice.toUtf8();
    char* priceStr = strdup(priceBytes.constData());
    clean_price_string(priceStr);
    data.price = QString(priceStr).toFloat();
    free(priceStr);

    // 复制字符串数据
    QByteArray modelBytes = modelEdit->text().toUtf8();
    strncpy(data.model, modelBytes.constData(), COMPONENT_MODEL_LEN - 1);
    data.model[COMPONENT_MODEL_LEN - 1] = '\0';

    QByteArray nameBytes = nameEdit->text().toUtf8();
    strncpy(data.name, nameBytes.constData(), COMPONENT_NAME_LEN - 1);
    data.name[COMPONENT_NAME_LEN - 1] = '\0';

    QByteArray packageBytes = packageEdit->text().toUtf8();
    strncpy(data.package, packageBytes.constData(), COMPONENT_PACKAGE_LEN - 1);
    data.package[COMPONENT_PACKAGE_LEN - 1] = '\0';

    // 处理描述，如果为空则填充默认值
    QString desc = descEdit->text().trimmed();
    if (desc.isEmpty()) {
        strcpy(data.description, "待完善");
    } else {
        QByteArray descBytes = desc.toUtf8();
        strncpy(data.description, descBytes.constData(), COMPONENT_DESCRIPTION_LEN - 1);
        data.description[COMPONENT_DESCRIPTION_LEN - 1] = '\0';
    }

    // 使用后端验证函数进行完整验证（包含供应商存在性检查）
    char error_msg[512];
    if (!validate_component_data_with_suppliers(&data, supplierHead, error_msg, sizeof(error_msg))) {
        QMessageBox::warning(this, "数据验证失败", QString("验证错误：%1").arg(error_msg));
        return;
    }

    // 库存为0时的特殊提示
    if (data.quantity == 0) {
        int ret = QMessageBox::question(this, "库存提醒",
                                       "当前库存为0，该组件将标记为缺货状态。是否继续？",
                                       QMessageBox::Yes | QMessageBox::No);
        if (ret == QMessageBox::No) {
            return;
        }
    }

    // 如果所有验证都通过，则接受对话框
    qDebug() << "ComponentDialog::accept() - Data before QDialog::accept():";
    qDebug() << "  ID:" << data.id;
    qDebug() << "  Model:" << data.model;
    qDebug() << "  Name:" << data.name;
    qDebug() << "  Package:" << data.package;
    qDebug() << "  Description:" << data.description;
    qDebug() << "  Quantity:" << data.quantity;
    qDebug() << "  Price:" << data.price;
    qDebug() << "  Supplier ID:" << data.supplier_id;
    QDialog::accept();
}